angular.module('BaseServer')

//我们把socket服务定义成了一个factory，这样它只会被实例化一次，而且在整个应用的作用域范围内就成为了一个单例
.factory('PublicSocket', ['BaseService', function(BaseService) {
	return function(){
		this.Socket = null;
		var self = this;
		BaseService.getSysParameterValue('SocketPort', function(data){
			if(data == null){
				return;
			}
            else{
            	self.Socket = io.connect('http://' + document.location.hostname + ":" + data);

            	//监听接收消息
				self.on = function(eventName, callback){
					if(self.Socket) {
						self.Socket.on(eventName, function(data){
							callback(data);
						});
					}
					else{
						var newErr = {
		                    leval: 5,
		                    title: 'Socket连接失败',
		                    message: 'Socket连接失败，请检查服务器是否正常'
		                }
		                PublicFunction.errFun(newErr);
					}
				};
				//发送消息
				self.emit = function(eventName, data) {
					if (self.Socket) {
						self.Socket.emit(eventName, data);
					}
				};
				//发给自己
				self.toSelf = function(eventName, sendData) {
			      if (self.Socket) {
			      	var data = {
			      		EventName: eventName,
			      		Data: sendData
			      	};
			        self.Socket.emit("toSelf", data);
			      }
		    	};
		    	//发给除自己的所有人
		    	self.toOther = function(eventName, sendData) {
			      if (self.Socket) {
			      	var data = {
			      		EventName: eventName,
			      		Data: sendData
			      	};
			        self.Socket.emit("toOther", data);
			      }
		    	};
		    	//发给所有人，包括自己
		    	self.toAll = function(eventName, sendData) {
			      if (self.Socket) {
			      	var data = {
			      		EventName: eventName,
			      		Data: sendData
			      	};
			        self.Socket.emit("toAll", data);
			      }
		    	};
		    	//加入房间
		    	self.joinRoom = function(roomName) {
			      if (self.Socket) {
			      	var data = {
			      		RoomName: roomName
			      	};
			        self.Socket.emit("joinRoom", data);
			      }
		    	};
		    	//离开房间
		    	self.leaveRoom = function(roomName) {
			      if (self.Socket) {
			      	var data = {
			      		RoomName: roomName
			      	};
			        self.Socket.emit("leaveRoom", data);
			      }
		    	};
		    	//向指定房间发送消息，不包括自己
		    	self.toRoom = function(roomName, eventName, sendData) {
			      if (self.Socket) {
			      	var data = {
			      		RoomName: roomName,
			      		EventName: eventName,
			      		Data: sendData
			      	};
			        self.Socket.emit("toRoom", data);
			      }
		    	};
		    	//向指定房间发送消息，包括自己
		    	self.inRoom = function(roomName, eventName, sendData) {
			      if (self.Socket) {
			      	var data = {
			      		RoomName: roomName,
			      		EventName: eventName,
			      		Data: sendData
			      	};
			        self.Socket.emit("inRoom", data);
			      }
		    	};
		    	self.disconnect = function(){
		    		self.Socket.emit("clientDisconnect");
		    	};
            }
        });
	};
}]);